package com.szcinda.service.dto.notes;

import com.szcinda.repository.*;
import com.szcinda.service.SnowFlakeFactory;
import com.szcinda.service.dto.log.LogCreateDto;
import com.szcinda.service.dto.log.LogService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class NotesServiceImpl implements NotesService {

    private final NotesRepository notesRepository;
    private final SnowFlakeFactory snowFlakeFactory;
    private final UserRepository userRepository;
    private final LogService logService;

    public NotesServiceImpl(NotesRepository notesRepository, UserRepository userRepository, LogService logService) {
        this.notesRepository = notesRepository;
        this.userRepository = userRepository;
        this.logService = logService;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public void create(NotesCreateDto createDto) {
        Notes notes = new Notes();
        BeanUtils.copyProperties(createDto, notes);
        notes.setStatus(NotesStatus.UNFIX);
        notes.setId(snowFlakeFactory.nextId("NO"));
        notesRepository.save(notes);
        User user = userRepository.findById(createDto.getUserId());
        LogCreateDto logCreateDto = new LogCreateDto(user.getId(),user.getNickName(),"新增备忘录", notes.getTitle());
        logService.create(logCreateDto);
    }

    @Override
    public void fix(String id) {
        Notes notes = notesRepository.findById(id);
        notes.setStatus(NotesStatus.FIXED);
        notesRepository.save(notes);
        User user = userRepository.findById(notes.getUserId());
        LogCreateDto logCreateDto = new LogCreateDto(user.getId(),user.getNickName(),"已办备忘录", notes.getTitle());
        logService.create(logCreateDto);
    }

    @Override
    public List<Notes> getAll(String userId, String orgId) {
        return notesRepository.findByUserIdAndStatusOrderByCreateTimeDesc(userId, NotesStatus.UNFIX);
    }

    @Override
    public void del(String id) {
        Notes notes = notesRepository.findById(id);
        notesRepository.delete(notes);
        User user = userRepository.findById(notes.getUserId());
        LogCreateDto logCreateDto = new LogCreateDto(user.getId(),user.getNickName(),"删除备忘录", notes.getTitle());
        logService.create(logCreateDto);
    }
}
